package org.javacore.concurrent;

import java.util.concurrent.*;

/**
 * Created by IntelliJ IDEA.
 * User: Fan
 * Date: 2019/9/15
 * Time: 16:19
 * Description: Semaphore实现按顺序打印
 * @author G7
 */
public class SemaphoreB {
	private final int max;
	// 从线程 A 开始执行
	//关键点说明
	//信号量初始化：A的信号量初始为1，B和C为0，确保A先执行
	//信号量传递：每个线程打印完后释放下一个线程的信号量
	//循环控制：通过循环次数控制总共打印多少轮
	//线程安全：Semaphore保证了线程间的同步和顺序
	private final Semaphore semaphoreA = new Semaphore(1);
	private final Semaphore semaphoreB = new Semaphore(0);
	private final Semaphore semaphoreC = new Semaphore(0);

	public SemaphoreB(int max) {
		this.max = max;
	}

	public void printA() {
		print("A", semaphoreA, semaphoreB);
	}

	public void printB() {
		print("B", semaphoreB, semaphoreC);
	}

	public void printC() {
		print("C", semaphoreC, semaphoreA);
	}

	private void print(String alphabet, Semaphore currentSemaphore, Semaphore nextSemaphore) {
		for (int i = 1; i <= max; i++) {
			try {
				currentSemaphore.acquire();
				System.out.println(alphabet);
				// 传递信号给下一个线程
				nextSemaphore.release();
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				return;
			}
		}
	}


	public static void main(String[] args) {
		SemaphoreB printer = new SemaphoreB(10);
		Thread t1 = new Thread(printer::printA);
		Thread t2 = new Thread(printer::printB);
		Thread t3 = new Thread(printer::printC);

		t1.start();
		t2.start();
		t3.start();
	}

}
